﻿using common;
using MS_Entity;
using MS_UI.HardwareConfig;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace MS_UI
{
    public partial class IOManger : Form
    {
        public IOManger()
        {

            InitializeComponent();
            this.dataGridView1.AutoGenerateColumns = false;
            this.Load += InitParams;
        }

        private void InitParams(object sender, EventArgs e)
        {
           
            VarList = ReadXML().ToList();
            varAlarm_Modbus = ReadXMLAlarm().ToList();
            UpdateData();
        }
        //页面重绘的时候，执行方法
        private void UpdateData()
        {
            throw new NotImplementedException();
        }

        private void myBtn1_Load(object sender, EventArgs e)
        {

        }
        //变量集合
        private List<Variable_Modus> VarList = new List<Variable_Modus>();
        //报警集合
        private List<VarAlarm_Modbus> varAlarm_Modbus = new List<VarAlarm_Modbus>();
        private void myBtn1_ClickHand(object sender, EventArgs e)
        {


            var wind = new NewVar();
            wind.ShowDialog();
            if (wind.DialogResult == DialogResult.OK)
            {
                VarList.Add(wind.variables);
                if (wind.varAlarms != null)
                {
                    varAlarm_Modbus.Add(wind.varAlarms);
                }

            }

            UpdateDGV();

        }
        private void UpdateDGV()
        {
            this.BeginInvoke(new Action(() =>
            {
                this.dataGridView1.DataSource = null;
                this.dataGridView1.DataSource = VarList;
            }));


        }

        private void myBtn2_Load(object sender, EventArgs e)
        {

        }

        //保存
        private void myBtn4_Load(object sender, EventArgs e)
        {

        }

        private void myBtn41_Load(object sender, EventArgs e)
        {

        }

        private void myBtn4_Click(object sender, EventArgs e)
        {

        }

        private void myBtn4_Load_1(object sender, EventArgs e)
        {

        }
        //参数 variabel
        string path1 = Application.StartupPath + @"\Variable_Modbus.xml";
        // 报警参数
        string path2 = Application.StartupPath + @"\VarAlarm_Modbus.xml";
        //存储区域参数
        string path3 = Application.StartupPath + @"\StoreArea_Modbus.xml";
        private void WriteTxt(string path, dynamic VarList)
        {
            XmlDocument rootxml = new XmlDocument();
            var root = rootxml.CreateElement("Root");
            foreach (var item in VarList)
            {
                XmlElement xmle = rootxml.CreateElement("Variable");
                //
                Tools.XMLAttributeAppend(rootxml, "VarName", item.VarName, xmle);
                Tools.XMLAttributeAppend(rootxml, "Address", item.Address, xmle);
                Tools.XMLAttributeAppend(rootxml, "DataType", item.DataType, xmle);
                Tools.XMLAttributeAppend(rootxml, "StoreArea", item.StoreArea, xmle);
                Tools.XMLAttributeAppend(rootxml, "Note", item.Note, xmle);
                Tools.XMLAttributeAppend(rootxml, "IsFilling", item.IsFiling + "", xmle);
                Tools.XMLAttributeAppend(rootxml, "IsAlarm", item.IsAlarm + "", xmle);
                Tools.XMLAttributeAppend(rootxml, "IsReport", item.IsReport, xmle);
                Tools.XMLAttributeAppend(rootxml, "AbsoluteAddress", item.AbsoluteAddress, xmle);
                root.AppendChild(xmle);
            }
            rootxml.AppendChild(root);
            try
            {
                //  rootxml.Save(Application.StartupPath + @"\Variable_Modbus.xml");
                rootxml.Save(path);
                MessageBox.Show("保存成功！");
            }
            catch
            {
                MessageBox.Show("保存失败！");
            }
        }
        //保存按钮
        private void myBtn4_ClickHand(object sender, EventArgs e)
        {
            var c = new Comon();
            //保存变量参数和 区域存储
            var rootxml = c.WriteVariable(VarList);
            var rootxml2 =  c.WriteStoreArea( Calculate());
            var rootxml3 = c.WriteVarAlarm(varAlarm_Modbus);
            try
            {
                //  rootxml.Save(Application.StartupPath + @"\Variable_Modbus.xml");
                rootxml.Save(path1);
                rootxml2.Save(path3);
                rootxml3.Save(path2);
                MessageBox.Show("保存成功！");
            }
            catch
            {
                MessageBox.Show("保存失败！");
            }
        }

        private void myBtn3_Load(object sender, EventArgs e)
        {

        }

        private void myBtn3_ClickHand(object sender, EventArgs e)
        {
            var res = MessageBox.Show("是否全部删除?", "确认", MessageBoxButtons.YesNo);
            if (res == DialogResult.Yes)
            {
                VarList.Clear();
            }
            this.BeginInvoke(new Action(() => { dataGridView1.DataSource = null; }));

        }
        private int GetMax(List<int> intList)
        {
            int temp = intList[0];
            foreach (int item in intList)
            {
                if (item > temp)
                {
                    temp = item;
                }
            }
            return temp;
        }
        /// <summary>
        /// 获取最小值
        /// </summary>
        /// <param name="intList"></param>
        /// <returns></returns>
        /// 
        //读取xml文件数据 variable
        private IEnumerable<Variable_Modus> ReadXML()
        {
            var c = new Comon();
            List<Variable_Modus> res ;
            XmlDocument xd = new XmlDocument();
            xd.Load(path1);
            res = c.GetVariable(xd);

            return res;
        }
        //读取 xml数据 VarAlarm
        private IEnumerable<VarAlarm_Modbus> ReadXMLAlarm()
        {
            var c = new Comon();
            List<VarAlarm_Modbus> res;
            XmlDocument xd = new XmlDocument();
            xd.Load(path2);
            res = c.GetVarAlarm(xd);

            return res;
        }
        #region 引用无意义
        private int GetMin(List<int> intList)
        {
            int temp = intList[0];
            foreach (int item in intList)
            {
                if (item < temp)
                {
                    temp = item;
                }
            }
            return temp;
        }
        private List<int> AnalyseVar(List<Variable_Modus> list)
        {
            List<int> ResultList = new List<int>(2);
            List<int> AddressList = new List<int>();
            int Start = 0;
            int End = 0;
            int Length = 0;
            string DataType = string.Empty;
            foreach (Variable_Modus item in list)
            {
                AddressList.Add(int.Parse(item.Address));
            }
            Start = GetMin(AddressList);
            End = GetMax(AddressList);
            foreach (Variable_Modus item in list)
            {
                if (item.Address == End.ToString())
                {
                    DataType = item.DataType;
                }
            }
            switch (DataType)
            {
                case "Bool":
                    Length = End - Start + 1;
                    break;
                case "Float":
                    Length = End - Start + 2;
                    break;
                case "Float Inverse":
                    Length = End - Start + 2;
                    break;
                case "Long":
                    Length = End - Start + 2;
                    break;
                case "Long Inverse":
                    Length = End - Start + 2;
                    break;
                case "Double":
                    Length = End - Start + 4;
                    break;
                case "Double Inverse":
                    Length = End - Start + 4;
                    break;
                default:
                    Length = End - Start + 2;
                    break;

            }
            ResultList.Add(Start);
            ResultList.Add(Length);
            return ResultList;

        }
        #endregion
        #region Calculate 计算出 StoreArea的存储集合
        private List<StoreArea> Calculate()
        {
            List<StoreArea> StoreList = new List<StoreArea>();
            List<Variable_Modus> List_0x = new List<Variable_Modus>();
            List<Variable_Modus> List_1x = new List<Variable_Modus>();
            List<Variable_Modus> List_3x = new List<Variable_Modus>();
            List<Variable_Modus> List_4x = new List<Variable_Modus>();
            foreach (Variable_Modus item in this.VarList)
            {
                if (item.StoreArea == "01 Coil Status(0x)")
                {
                    List_0x.Add(item);
                }
                if (item.StoreArea == "02 Input Status(1x)")
                {
                    List_1x.Add(item);
                }
                if (item.StoreArea == "03 Holding Register(4x)")
                {
                    List_4x.Add(item);
                }
                if (item.StoreArea == "04 Input Registers(3x)")
                {
                    List_3x.Add(item);
                }
            }
            if (List_0x.Count > 0)
            {
                StoreList.Add(new StoreArea()
                {
                    StoreType = "01 Coil Status(0x)",
                    StartReg = AnalyseVar(List_0x)[0],
                    Length = AnalyseVar(List_0x)[1]
                });
            }
            if (List_4x.Count > 0)
            {
                StoreList.Add(new StoreArea()
                {
                    StoreType = "03 Holding Register(4x)",
                    StartReg = AnalyseVar(List_4x)[0],
                    Length = AnalyseVar(List_4x)[1]
                });
            }
            return StoreList;
        }

        #endregion
    }
}
